from PyQt5.QtWidgets import (
    QTableWidget,
    QHeaderView,
    QAbstractItemView,
    QTableWidgetItem,
    QLineEdit,
    QStyledItemDelegate,
)
from PyQt5.QtCore import pyqtSignal, Qt
from PyQt5.QtGui import QPainter, QPen, QColor, QDoubleValidator, QIntValidator
from .ui_style import UiStyle
from .util.type_conversion import TypeConversion
import gui.controls.envs as envs
from . import message_box as MBox


class FloatValidatorDelegate(QStyledItemDelegate):
    def __init__(self, parent=None):
        super(FloatValidatorDelegate, self).__init__(parent)
        self.validator = QDoubleValidator(self)

    def createEditor(self, parent, option, index):
        editor = QLineEdit(parent)  # 使用 QLineEdit 作为编辑器
        editor.setValidator(self.validator)
        return editor


class IntValidatorDelegate(QStyledItemDelegate):
    def __init__(self, parent=None):
        super(IntValidatorDelegate, self).__init__(parent)
        self.validator = QIntValidator(self)

    def createEditor(self, parent, option, index):
        editor = QLineEdit(parent)  # 使用 QLineEdit 作为编辑器
        editor.setValidator(self.validator)
        return editor


class CParamsTable(QTableWidget):
    item_changed_signal = pyqtSignal(object)

    def __init__(self, rows=0, columns=2, parent=None):
        super(CParamsTable, self).__init__(parent)
        self.setRowCount(rows)
        self.setColumnCount(columns)
        self.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        # 设置选择模式为单行选择
        self.setSelectionMode(QAbstractItemView.SingleSelection)
        # 不高亮标题
        self.horizontalHeader().setHighlightSections(False)
        # 垂直分割宽度
        self.verticalHeader().setSectionResizeMode(QHeaderView.Fixed)
        # 不高亮标题
        # self.verticalHeader().setVisible(False)
        # 设置表格控件的编辑触发器  表格不可编辑
        self.setEditTriggers(QAbstractItemView.NoEditTriggers)
        # 设置选中行为为选中整行
        self.setSelectionBehavior(QTableWidget.SelectRows)

        self.rowFloat = []
        self.rowInt = []

        # self.currentItemChanged.connect(self.on_current_item_changed)

        # UiStyle().tableHorHeader(self)

    def addRow(self, list):
        row_position = self.rowCount()  # 获取当前行数，以确定新行的位置
        self.insertRow(row_position)  # 在末尾插入一行
        for column_index, data in enumerate(list):
            if data is None:
                data = ""
            item = QTableWidgetItem(str(data))  # 将数据转换为 QTableWidgetItem
            item.setTextAlignment(Qt.AlignCenter)
            self.setItem(row_position, column_index, item)

    def delete_selected_row(self):
        # 获取当前选中的所有行
        # selected_ranges = self.selectedRanges()  # self是QTableWidget实例
        selected_rows = self.selectionModel().selectedRows()

        if not selected_rows:
            MBox.warning(text="请选择要删除的行！", btnTitle="关闭")
            return  # 如果没有选中的行，直接返回
        isDel = MBox.confirm(
            "是否确认删除当前选中行?",
        )
        if isDel:
            row = selected_rows[0].row()
            self.removeRow(row)

        # # 获取所有选中的行索引（考虑多选情况）
        # selected_rows = set()
        # for range_ in selected_ranges:
        #     selected_rows.update(range(row_range.topRow(), row_range.bottomRow() + 1))

        # 从大到小删除行，避免索引变化导致的问题
        # for row in sorted(selected_rows, reverse=True):
        #     self.removeRow(row)

    def deleteSelectedRow(self):
        selected_items = self.selectedItems()
        if not selected_items:
            MBox.warning("请选择要删除的行")
            return
        isDel = MBox.confirm(
            "是否确认删除当前选中行?",
        )
        if isDel:
            rows = set()
            for item in selected_items:
                rows.add(item.row())
            for row in sorted(rows, reverse=True):
                self.removeRow(row)

    def editSelectedRow(self):
        selected_items = self.selectedItems()
        if not selected_items:
            MBox.warning("请选择要编辑的行")
            return []
        row_index = selected_items[0].row()
        row_data = []
        for column in range(self.columnCount()):
            item = self.item(row_index, column)  # 获取单元格
            if item:
                row_data.append(item.text())  # 提取单元格文本
            else:
                row_data.append("")
        return row_data

    def updateRowWithData(self, labels=[]):
        # 获取当前选中项
        selected_items = self.selectedItems()
        if not selected_items:
            return  # 如果没有选中项，则返回
        row_index = selected_items[0].row()  # 获取选中行的索引
        # 校验传入的 labels 列表长度是否与列数相匹配
        if len(labels) != self.columnCount():
            print("错误: 提供的数据数量与列数不匹配")
            return

        # 更新指定行的数据
        for column_index in range(self.columnCount()):
            if labels[column_index] is None:
                labels[column_index] = ""
            item = QTableWidgetItem(
                str(labels[column_index])
            )  # 创建新的 QTableWidgetItem
            item.setTextAlignment(Qt.AlignCenter)  # 设置文本居中
            self.setItem(row_index, column_index, item)  # 更新表格中该行的单元格

    def setCellCenter(self):
        # 设置整个表格所有单元格居中
        for row in range(self.rowCount()):
            for col in range(self.columnCount()):
                item = self.item(row, col)
                if item:
                    item.setTextAlignment(Qt.AlignCenter)
                else:
                    item = QTableWidgetItem("")
                    item.setTextAlignment(Qt.AlignCenter)
                    self.setItem(row, col, item)

    def set_columns_editable(self):
        # # 设置第一列不可编辑
        # for row in range(self.rowCount()):
        #     cell = self.item(row, 0)
        #     if cell is None:
        #         cell = QTableWidgetItem(str(row + 1))
        #         cell.setTextAlignment(Qt.AlignCenter)
        #         self.setItem(row, 0, cell)
        #     cell.setFlags(cell.flags() & ~Qt.ItemIsEditable)

        # 设置其他列可编辑
        for col in range(self.columnCount()):
            for row in range(self.rowCount()):
                cell = self.item(row, col)
                if cell is None:
                    cell = QTableWidgetItem()
                    cell.setTextAlignment(Qt.AlignCenter)
                    self.setItem(row, col, cell)
                cell.setFlags(cell.flags() | Qt.ItemIsEditable)

    # def on_current_item_changed(self, current, previous):
    #     if current is not None:
    #         row = current.row()
    #         row_data = [self.item(row, col).text() for col in range(self.columnCount())]
    #         self.item_changed_signal.emit(row_data)

    # def addRowWithData(self, labels=[], isCenter=False):
    #     new_row_index = self.rowCount()
    #     self.insertRow(new_row_index)
    #     for column in range(self.columnCount()):
    #         item = QTableWidgetItem(labels[column])
    #         # if isCenter:
    #         item.setTextAlignment(Qt.AlignCenter)
    #         self.setItem(new_row_index, column, item)

    # def updateRowWithData(self, labels=[]):
    #     new_row_index = self.rowCount()
    #     self.insertRow(new_row_index)
    #     for column in range(self.columnCount()):
    #         item = QTableWidgetItem(labels[column])
    #         self.setItem(new_row_index, column, item)

    # def getSelectedRowData(self):
    #     selected_items = self.selectedItems()
    #     if not selected_items:
    #         return False
    #     row_data = [self.item(item.row(), col).text() for col in range(self.columnCount()) for item in selected_items]
    #     return row_data

    # def deleteSelectedRow(self):
    #     selected_items = self.selectedItems()
    #     if not selected_items:
    #         return
    #     isDel = MBox.confirm("是否确认删除当前选中行?")
    #     if isDel:
    #         rows = set()
    #         for item in selected_items:
    #             rows.add(item.row())
    #         for row in sorted(rows, reverse=True):
    #             self.removeRow(row)

    # def editSelectedRow(self):
    #     selected_items = self.selectedItems()
    #     if not selected_items:
    #         return
    #     row_index = selected_items[0].row()
    #     row_data = []
    #     for column in range(self.columnCount()):
    #         item = self.item(row_index, column)  # 获取单元格
    #         if item:
    #             row_data.append(item.text())  # 提取单元格文本
    #         else:
    #             row_data.append("")
    #     return row_data

    def rowSetInt(self, toInt):
        self.rowInt = toInt
        for row in toInt:
            self.setItemDelegateForColumn(row, IntValidatorDelegate(self))

    def rowSetFloat(self, toFloat):
        self.rowFloat = toFloat
        for row in toFloat:
            self.setItemDelegateForColumn(row, FloatValidatorDelegate(self))

    def getRuleValue(self, value, column):
        if column in self.rowFloat:
            return TypeConversion.toFloat(value)
        elif column in self.rowInt:
            return TypeConversion.toInt(value)
        else:
            return str(value) if value else ""
